var firstNameGlobal;
var lastNameGlobal;
var currentQuadrant;
var empQuadrant;
var currentRow;
var currentColumn;
var pmRow;
var isPm;

// Bind events
$(document).ready(function() {

	settings = {
		// zoomed size relative to the container element
		// 0.0-1.0
		targetsize : .1,
		// animation duration
		duration : 450,
		// easing of animation, similar to css transition params
		// "linear"|"ease"|"ease-in"|"ease-out"|"ease-in-out"|[p1,p2,p3,p4]
		// [p1,p2,p3,p4] refer to cubic-bezier curve params
		easing : "ease",
		root : $("#searchMap")
	};

	settings2 = {
		// zoomed size relative to the container element
		// 0.0-1.0
		targetsize : .2,
		// animation duration
		duration : 450,
		// easing of animation, similar to css transition params
		// "linear"|"ease"|"ease-in"|"ease-out"|"ease-in-out"|[p1,p2,p3,p4]
		// [p1,p2,p3,p4] refer to cubic-bezier curve params
		easing : "ease",
		root : $("#searchMap")
	};

	$("#searchQuery").keyup(function(e) {
		if (e.which == 13) {
			$("#searchBtn").click();
		}
	});

	// variables
	$("#searchBtn").click(function(evt) {

		$(".content").hide();
		$("#searchResultsContainer").show("drop", {
			direction : "right"
		}, 500);

		var $query = $("#searchQuery").val();
		var $ResultsBox = $('#resultsBox');
		var $searchFor = $('#searchFor');

		$ResultsBox.empty();
		$searchFor.empty();
		$('<span>').html("Results for: " + $query).appendTo($searchFor);
		getWildCard($query);
		
		$ResultsBox.children('results').first().addClass('chosenResult');

		// var $results = ;
		// firstNameGlobal = $('#resultsBox
		// .result').first().children('span .firstName').text();
		// lastNameGlobal = $('#resultsBox
		// .result').first().children('span .lastName').text();
		// firstNameGlobal =
		// $results.children('.firstName').text();
		// lastNameGlobal =
		// $results.children('.lastName').text();

	});


//	$( "#resultsBox .result" ).on("click", function( event ) {
//		$(".result").removeClass('chosenResult');
//		$(this).addClass('chosenResult');
//		firstNameGlobal = $(this).children(' span .firstName').text();
//		lastNameGlobal = $(this).children(' span .lastName').text();
//		getEmployeeDetails(firstNameGlobal, lastNameGlobal);
//		evt.stopPropagation();
//	});
	
	$('#resultsBox').on('click', '.result', function(evt) {
		$(".result").removeClass('chosenResult');
		$(this).addClass('chosenResult');
		firstNameGlobal = $(this).children('.firstName').text();
		lastNameGlobal = $(this).children('.lastName').text();
		getEmployeeDetails(firstNameGlobal, lastNameGlobal);
		evt.stopPropagation();
	});

	// $(".seatColumn").click(function (evt) {

	// $(this).zoomTo(settings2);
	// });

	$("#unzoom").click(function(evt) {
		var name = $(this).children('span').text();
		zoomOut();
		evt.stopPropagation();

	});

	$('#searchMap').dragscrollable({
		dragSelector : '#searchMap:first'
	});

	$('#searchMap').kinetic();

	$("#closeSearchBtn").click(function(evt) {

		$("#searchResultsContainer").hide("drop", {
			direction : "right"
		}, 500);
		$(".content").show("drop", {
			direction : "right"
		}, 500);

	});

});

function zoomOut() {
	$("#searchMap").removeClass('visibleFlow');
	$("#searchMap").zoomTo(settings);

}

function chooseResult(element) {

}

// AJAX Function for getting wildcard search

function getWildCard(query) {

	$.ajax({
		url : '/PeopleLocatorSystem/SearchServlet',
		data : {
			searchQuery : query
		},
		success : function(responseJson) {
			mapQueryResponse(responseJson);

			getEmployeeDetails(firstNameGlobal, lastNameGlobal);

		},
		error : function(e) {
			alert("Error connecting to server.");
		}
	});

}

// Function for mapping the respionse to the UI
function mapQueryResponse(responseJson) {

	if (responseJson["exceptionError"] != null) {
		// Do alert here
		alert(responseJson["exceptionError"].message);

	} else if (responseJson["validationError"] != null) {
		var valErrors = [];
		$.each(responseJson["validationError"], function() {
			valErrors.push(responseJson["validationError"].message);
		});
		alert(valErrors.join(","));
	} else if (responseJson["searchResults"].length == 0) {
		var $ResultsBox = $('#resultsBox');
		$('<div class="result">').html("No results found.").appendTo(
				$ResultsBox);
	} else {
		var $ResultsBox = $('#resultsBox');
		$.each(responseJson.searchResults, function() {
			// var $firstName = $('<span class="firstName">')
			// .text(this.firstName);
			// var $lastName = $('<span class="lastName">').text(
			// this.lastName);
			// $('<div class="result">')
			// .html(this.firstName + " " +
			// this.lastName).appendTo(
			// $ResultsBox);
			$ResultsBox.append('<div class="result"> <span class="firstName">'
					+ this.firstName + '</span>&nbsp<span class="lastName">'
					+ this.lastName + '</span></div>');

		});

		firstNameGlobal = responseJson.searchResults[0].firstName;
		lastNameGlobal = responseJson.searchResults[0].lastName;
	}

}

// AJAX Function for getting the employee details
function getEmployeeDetails() {

	$.ajax({
		url : '/PeopleLocatorSystem/GetEmployeeDetailsServlet',
		data : {
			firstName : firstNameGlobal,
			lastName : lastNameGlobal
		},
		success : function(responseJson) {
			mapEmployeeDetails(responseJson);
			getSeatMap(empQuadrant);

		},
		error : function(e) {
			alert("Error connecting to server.");
		}
	});

}

// Function for mapping the employee details
function mapEmployeeDetails(responseJson) {
	var employee = responseJson.employeeDetail.employee;
	var seat = responseJson.employeeDetail.seatDetails;
	clearInfoBox();

	empQuadrant = seat.quadrant;
	currentColumn = seat.seatColumn;
	currentRow = seat.seatRow;
	pmRow = seat.seatCode;

	$('<span>').text("Name: " + employee.firstName + " " + employee.lastName)
			.appendTo($('#infoName'));
	$('<span>').text("EmployeeId: " + employee.employeeId).appendTo(
			$('#infoEmployeeId'));
	$('<span>').text("Email: " + employee.emailAddress).appendTo(
			$('#infoEmail'));
	$('<span>').text("Seat code: " + seat.seatCode)
			.appendTo($('#infoSeatCode'));
	var local = (seat.localNumber == 0 ? "none" : seat.localNumber);
	$('<span>').text("Local number: " + local).appendTo($('#infoLocal'));

}

// AJAX function for getting the search seat map
function getSeatMap(empQuadrant) {

	$.ajax({
		url : '/PeopleLocatorSystem/GetSearchSeatMapServlet',
		data : {
			firstName : firstNameGlobal,
			lastName : lastNameGlobal
		},
		success : function(responseJson) {
			getQuadrant(responseJson, empQuadrant);
		},
		error : function(e) {
			alert("Error connecting to server.");
		}
	});

}

function getQuadrant(responseJson, empQuadrant) {
	if (empQuadrant == currentQuadrant) {
		zoomToSeat(currentColumn, currentRow);
	} else {
		if (empQuadrant == "QUADRANT A") {
			getQuadrantA(responseJson);
			currentQuadrant = empQuadrant;
			// zoomToSeat(currentColumn, currentRow);
		} else if (empQuadrant == "QUADRANT B") {
			getQuadrantB(responseJson);
			currentQuadrant = empQuadrant;
			// zoomToSeat(currentColumn, currentRow);
		} else if (empQuadrant == "QUADRANT C") {
			getQuadrantC(responseJson);
			currentQuadrant = empQuadrant;
			// zoomToSeat(currentColumn, currentRow);
		} else if (empQuadrant == "QUADRANT D") {
			getQuadrantD(responseJson);
			currentQuadrant = empQuadrant;
			// zoomToSeat(currentColumn, currentRow);
		}
	}

}

//
// get seatmap and vamp the values
function getQuadrantA(responseJson) {

	$('#searchMap').load(
			'/PeopleLocatorSystem/pages/search/quadrantA.jsp .quadrant',
			function() {
				mapToSeat(responseJson);
				mapPms(responseJson);
				zoomToSeat(currentColumn, currentRow, pmRow);
			});

}

function getQuadrantB(responseJson) {

	$('#searchMap').load(
			'/PeopleLocatorSystem/pages/search/quadrantB.jsp .quadrant',
			function() {
				mapToSeat(responseJson);
				mapPms(responseJson);
				zoomToSeat(currentColumn, currentRow, pmRow);
			});

}

function getQuadrantC(responseJson) {

	$('#searchMap').load(
			'/PeopleLocatorSystem/pages/search/quadrantC.jsp .quadrant',
			function() {
				mapToSeat(responseJson);
				mapPms(responseJson);
				zoomToSeat(currentColumn, currentRow, pmRow);
			});

}

// get seatmap and vamp the values
function getQuadrantD(responseJson) {

	$('#searchMap').load(
			'/PeopleLocatorSystem/pages/search/quadrantD.jsp .quadrant',
			function() {
				mapToSeat(responseJson);
				mapPms(responseJson);
				zoomToSeat(currentColumn, currentRow, pmRow);
			});

}

function mapToSeat(responseJson) {
	$.each(responseJson.workstationList, function() {
		// $("#searchMap .seat").find("[data-slide='" + current + "']");
		$currentSeat = $("#searchMap .seatColumn[data-column='"
				+ this.seatDetails.seatColumn + "'] .seat[data-seat='"
				+ this.seatDetails.seatRow + "']");

		$currentSeat.children('.seatCode').html(this.seatDetails.seatCode);

		var firstName = this.employee.firstName == null ? "Unallocated"
				: this.employee.firstName;
		var lastName = this.employee.lastName == null ? "Seat"
				: this.employee.lastName;
		var local = this.seatDetails.localNumber == 0 ? ""
				: this.seatDetails.localNumber;
		var projectList = this.projectList == null ? "" : this.projectList;

		$currentSeat.children('.resource').append(
				'<div>' + firstName + " " + lastName + '</div>');

		$currentSeat.children('.local').html(local);

		if (projectList != "") {
			$.each(projectList, function() {
				$currentSeat.children('.project').append(
						'<div>' + this.projectName + '</div>');
			});
		}
	});

}

function zoomToSeat(column, row, pmrow) {

	if (pmRow.length < 5) {
		zoomToPm(pmRow);
	} else {
		zoomToEmp(column, row);
	}
}

function zoomToPm(pmrow) {
	$(".seat").removeClass('chosenSeat');
	$(".pmCube").removeClass('chosenSeat');

	$("#searchMap").addClass('visibleFlow');
	// $(".seat .resource div:contains(" + firstName + " " + lastName +
	// ")").parent(
	// '.seat').addClass('chosenSeat').zoomTo(settings2);
	// $(".seat > .resource div:contains(" + firstName + " " + lastName +
	// ")").parent(
	// '.resource').parent('.seat').addClass('chosenSeat').zoomTo(settings2);

	$currentSeat = $("#searchMap .pmCube[data-seat='" + pmRow + "']");

	$currentSeat.addClass('chosenSeat').zoomTo(settings2);

}

// zooms to seat
function zoomToEmp(column, row) {
	$(".seat").removeClass('chosenSeat');
	$(".pmCube").removeClass('chosenSeat');

	$("#searchMap").addClass('visibleFlow');
	// $(".seat .resource div:contains(" + firstName + " " + lastName +
	// ")").parent(
	// '.seat').addClass('chosenSeat').zoomTo(settings2);
	// $(".seat > .resource div:contains(" + firstName + " " + lastName +
	// ")").parent(
	// '.resource').parent('.seat').addClass('chosenSeat').zoomTo(settings2);

	$currentSeat = $("#searchMap .seatColumn[data-column='" + column
			+ "'] .seat[data-seat='" + row + "']");

	$currentSeat.addClass('chosenSeat').zoomTo(settings2);

}

function mapPms(responseJson) {
	$.each(responseJson.workstationList, function() {
		// $("#searchMap .seat").find("[data-slide='" + current + "']");
		$currentSeat = $("#searchMap .pmCube[data-seat='"
				+ this.seatDetails.seatCode + "']");

		$currentSeat.children('.seatCode').html(this.seatDetails.seatCode);

		var firstName = this.employee.firstName == null ? "Unallocated"
				: this.employee.firstName;
		var lastName = this.employee.lastName == null ? "Seat"
				: this.employee.lastName;
		var local = this.seatDetails.localNumber == 0 ? ""
				: this.seatDetails.localNumber;
		var projectList = this.projectList == null ? "" : this.projectList;

		$currentSeat.children('.pmResource').append(
				'<div>' + firstName + " " + lastName + '</div>');

		$currentSeat.children('.local').html(local);

		if (projectList != "") {
			$.each(projectList, function() {
				$currentSeat.children('.project').append(
						'<div>' + this.projectName + '</div>');
			});
		}
	});

}

function clearInfoBox() {
	$('#infoName').empty();
	$('#infoEmployeeId').empty();
	$('#infoEmail').empty();
	$('#infoSeatCode').empty();
	$('#infoLocal').empty();

}
